import React, { useMemo, useState, useTransition } from 'react'

export default function UseTransitionDemo() {
  const [isPending, startTransition ] = useTransition()
  const [rangeValue, setRangeValue] = useState(1)
  const [renderData, setRenderData] = useState([1])
  const [isTransition, setIsTransition] = useState(false)

  const handleChange = (e) => {
    setRangeValue(e.target.value)

    const arr = []
    arr.length = e.target.value
    for (let i = 0; i <= arr.length; i++) {
      arr.fill(i, i + 1)
    }

    if (isTransition) {
      // 把 setRenderData(arr) 标记为非紧急任务
      startTransition(() => {
        setRenderData(arr)
      })
    } else {
      setRenderData(arr)
    }
  }

  const jsx = useMemo(() => {
    // renderData
    return (
      <>
      {
        renderData.map((item, index) => {
          return (
            <div
            style={{
              width: 50,
              height: 50,
              backgroundColor: `#${Math.floor(Math.random() * 16777215).toString(
                16
              )}`,
              margin: 10,
              display: 'inline-block',
            }}
            key={'item'+index}
          >
            {item}
          </div>
          )
        })
      }
    </>
  )
  }, [renderData])

  return (
    <>
      <div>
        <input 
          type="checkbox"
          value={isTransition}
          onChange={() => setIsTransition(!isTransition)}
        />
      useTransition -
        <span>{JSON.stringify(isPending)}</span>
      </div>
      <div>
        <input
          type="range"
          value={rangeValue}
          min={0}
          max={10000}
          style={{ width: 120 }}
          onChange={handleChange} />
          <span> {rangeValue} </span>
      </div>
      {jsx}
    </>
  )
}
